package container

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils/rpc"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	pbAuthorizationAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/authorizationAdmin"
	"strconv"
	"strings"
)

type Auth struct {
	Data           *pbAuthorizationAdmin.PermissionResp
	allowResources []interface{}
}

func (a *Auth) Init(ctx context.Context, token, resource string) (bool, *businessError.ErrorInfo) {
	tokenData := strings.Split(token, "-")
	if len(tokenData) < 2 {
		return false, nil
	}

	Id, _ := strconv.ParseInt(tokenData[0], 10, 64)
	Token := tokenData[1]

	row, e := rpc.GetAuthorizationAdminClient().Permission(ctx, &pbAuthorizationAdmin.PermissionReq{
		Id:       Id,
		Resource: resource,
	})

	if e != nil {
		return false, businessError.RpcErrorToErrorInfo(e)
	}

	if row == nil {
		return false, nil
	}

	if row.Admin.Token != Token {
		return false, nil
	}

	a.Data = row

	return true, nil
}

func (a *Auth) SetAllowResources(allowResources []interface{}) {
	a.allowResources = allowResources
}

func (a *Auth) Permission() bool {
	return a.Data.Permission
}
